package com.wzh.forxu.utils;

import android.support.compat.BuildConfig;
import android.text.TextUtils;
import android.util.Log;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * @Author Hu$
 * @Time 2017/3/23$ .15:35$.
 * @Email 87683202@qq.com
 */
public class HttpApi {
    private static HttpApi instance;
    private Retrofit retrofit;
    //请求时间
    private static final int DEFAULT_TIMEOUT = 10;

    public HttpApi(String url) {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)

                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);


        //如果不是在正式包，添加拦截 打印响应json
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(
                    new HttpLoggingInterceptor.Logger() {
                        @Override
                        public void log(String message) {
                            if (TextUtils.isEmpty(message)) return;
                            String s = message.substring(0, 1);
                            //如果收到想响应是json才打印
                            Log.e("收到响应: ", "" + message);
//                            if ("{".equals(s) || "[".equals(s)) {
//                                Log.e("收到响应: ", "" + message);
//                            }
                        }
                    });
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClientBuilder.addInterceptor(logging);
        }
        retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(httpClientBuilder.build())
                //增加返回值为String的支持
                .addConverterFactory(ScalarsConverterFactory.create())
                //增加返回值为Gson的支持(以实体类返回)
                .addConverterFactory(GsonConverterFactory.create())
                //增加返回值为Oservable<T>的支持
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public static HttpApi getInstance(String url) {
        if (instance == null) {
            synchronized (HttpApi.class) {
                if (instance == null) {
                    instance = new HttpApi(url);
                }
            }
        }
        return instance;
    }

    public <T> T getService(Class<T> service) {
        return retrofit.create(service);
    }
}
